package easypsync.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;
import easypsync.ics.Calendar;
import easypsync.ics.Event;

public class SyncCalendar {
	
	private final String TAG = SyncCalendar.class.getName();

	Context context;
	
	String outputFilePath;

	public SyncCalendar(Context context) {
		super();
		this.context = context;
	}
	
	public void sync() {
		try {
			int calendarID = getDefaultCalendar();

			File root = Environment.getExternalStorageDirectory();
//			Log.i(TAG, root.getAbsolutePath());
			if (!root.canWrite()) {
				Log.e(TAG, "CANNOT WRITE");
			}
			File subdir = new File(root, "pimBackup");
			subdir.mkdirs();
			File f = new File(subdir, "calendar.ics");
			f.createNewFile();

			outputFilePath = f.getAbsolutePath();
			
			Calendar c = new Calendar();

			if (calendarID != 0) {
				addAllEvents(c, calendarID);
			} else {
				Log.i(TAG, "Default calendar not found.");
			}

			OutputStream os = new FileOutputStream(f);
			c.write(os);
			os.close();

		} catch (Exception e) {
			Log.e(TAG, "General failure", e);
		}
		
		transferFile();
	}
	
	private int getDefaultCalendar() {
		int result = 0;
		String[] projection = new String[] { "_id", "name" };
		String selection = "selected=1";
		String path = "calendars";

		Cursor managedCursor = getCalendarManagedCursor(projection, selection, path);

		if (managedCursor != null && managedCursor.moveToFirst()) {
//			int nameColumn = managedCursor.getColumnIndex("name");
			int idColumn = managedCursor.getColumnIndex("_id");

			do {
//				String calName = managedCursor.getString(nameColumn);
				String calId = managedCursor.getString(idColumn);
//				if (Log.isLoggable(TAG, Log.DEBUG))
//					Log.d(TAG, "Found Calendar '" + calName + "' (ID=" + calId + ")");
				if (calId != null && calId.equals("1")) {
					result = Integer.parseInt(calId);
				}
			} while (managedCursor.moveToNext());
		} else {
			Log.i(TAG, "No Calendars found");
		}

		return result;

	}

	private void addAllEvents(Calendar c, int calID) throws IOException {

		Cursor managedCursor = getCalendarManagedCursor(null, "calendar_id=" + calID, "events");

		if (managedCursor != null && managedCursor.moveToFirst()) {
			do {
				Event e = new Event();
				for (int i = 0; i < managedCursor.getColumnCount(); i++) {
					if (managedCursor.getColumnName(i).equals("iCalGUID"))
						e.setUid(managedCursor.getString(i));
					else if (managedCursor.getColumnName(i).equals("title"))
						e.setSummary(managedCursor.getString(i));
					else if (managedCursor.getColumnName(i).equals("dtstart"))
						e.setDtstart(new Date(managedCursor.getLong(i)));
					else if (managedCursor.getColumnName(i).equals("dtend"))
						e.setDtend(new Date(managedCursor.getLong(i)));
					else if (managedCursor.getColumnName(i).equals("eventLocation"))
						e.setLocation(managedCursor.getString(i));
					else if (managedCursor.getColumnName(i).equals("lastDate"))
						e.setDtstamp(new Date(managedCursor.getLong(i)));
				}

				c.addEvent(e);
			} while (managedCursor.moveToNext());
		} else {
			Log.i(TAG, "No Calendars");
		}
	}

	/**
	 * @param projection
	 * @param selection
	 * @param path
	 * @return
	 */
	private Cursor getCalendarManagedCursor(String[] projection, String selection, String path) {
		Uri calendars = Uri.parse("content://calendar/" + path);

		Cursor managedCursor = null;
		try {
			ContentResolver cr = context.getContentResolver();
			managedCursor = cr.query(calendars, projection, selection, null, null);
		} catch (IllegalArgumentException e) {
			Log.w(TAG, "Failed to get provider at [" + calendars.toString() + "]");
		}

		if (managedCursor == null) {
			// try again
			calendars = Uri.parse("content://com.android.calendar/" + path);
			try {
				ContentResolver cr = context.getContentResolver();
				managedCursor = cr.query(calendars, projection, selection, null, null);
			} catch (IllegalArgumentException e) {
				Log.w(TAG, "Failed to get provider at [" + calendars.toString() + "]");
			}
		}
		return managedCursor;
	}

	private void transferFile() {
		SMBTransfer.transferFile(outputFilePath, "calendar.ics");
	}
}
